package com.mresources.web.controller;

import com.mresources.common.auth.Oauth2Config;
import com.mresources.common.dto.Result;
import com.mresources.common.dto.Token;
import com.mresources.web.service.Oauth2Service;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.Principal;

@RestController
@RequestMapping("/oauth2")
public class AuthController {
    @Resource
    private Oauth2Service oauth2Service;


    @GetMapping("/callback")
    public Result<Token> auth(@Param("code") String code, @Param("state") String state, HttpSession session) {
        Oauth2Config config = oauth2Service.getConfig();
        Token token = oauth2Service.getToken(config, code, state);
        if (token != null) {
            session.setAttribute("token", token);
        }
        return Result.success().withData(token);
    }

    @GetMapping("/principal")
    public Result<Principal> auth(Principal principal) {
        return Result.success().withData(principal);
    }

    @GetMapping("")
    public void redirectUrl(HttpServletResponse response, HttpSession session) throws IOException {
        if (session.getAttribute("token") != null) {
            response.sendRedirect("/home");
            return;
        }
        Oauth2Config config = oauth2Service.getConfig();
        String redirectUrl = response.encodeRedirectURL(config.generateOauth2Url());
        response.sendRedirect(redirectUrl);
    }

}
